Java switch Statement
In java, the switch
statement is used to check multiple conditions like else-if
statement.
The switch
statement will select one of the code blocks and executes it.
Syntax for switch statement
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Let us see a program to get a choice from the user, whether to perform addition or subtraction or division or multiplication. Then get 2 numbers from the user and perform the opertion based on the option provided.
Example program for switch statement
import java.util.*;
class Main {
public static void main(String[] args) {
int choice, a, b;
Scanner scanner = new Scanner(System.in);
System.out.println("Select an option:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Modulus");
System.out.println("6. Exit");
System.out.println("Enter your choice: ");
choice = scanner.nextInt();
System.out.println("Enter two numbers: ");
a = scanner.nextInt();
b = scanner.nextInt();
switch (choice) {
case 1:
System.out.printf("%d + %d = %d\n", a, b, (a + b));
break;
case 2:
System.out.printf("%d - %d = %d\n", a, b, (a - b));
break;
case 3:
System.out.printf("%d * %d = %d\n", a, b, (a * b));
break;
case 4:
System.out.printf("%d / %d = %d\n", a, b, (a / b));
break;
case 5:
System.out.printf("%d %% %d = %d\n", a, b, (a % b));
break;
case 6:
System.out.printf("Exiting...\n");
break;
default:
System.out.printf("Invalid choice\n");
}
}
}
Output
Select an option:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
6. Exit
Enter your choice:
3
Enter two numbers:
5 4
5 * 4 = 20
In the above program, we get the a choice from the user. Then provide the value to the switch
statement.
Now the case
statement will check whether the value is of the choice
is 1
.
If the choice is 1
, then it will perform addition on the variable a
and b
and breaks from the switch
block and moves out of the switch
block.
If the condition is not satisfied, then it will go to the next case
statement performs the check condition as above.
If no condition(s) are satisfied, then the default
statement will be executed.